<template>
  <div class="app-container">
    <el-row style="margin-bottom:30px;">
      <el-form ref="articleFormRef" :model="form" :rules="rules">
        <el-form-item hidden>
          <el-input v-model="form.articleId" hidden />
          <el-input v-model="form.status" hidden />
          <el-input v-model="form.thumbnail" hidden />
          <el-input v-model="form.source" hidden />
        </el-form-item>
        <el-col :span="22">
          <el-card shadow="always" class="mb-10">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-col :span="24">
                  <el-form-item prop="title">
                    <el-input v-model="form.title" placeholder="文章标题" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="summary">
                    <el-input
                      v-model="form.summary"
                      type="textarea"
                      placeholder="文章摘要"
                      :rows="2"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-row>
                    <el-form-item prop="channel">
                      <el-col :span="4">
                        <span>栏目</span>
                      </el-col>
                      <el-col :span="16">
                        <el-select v-model="form.channel">
                          <el-option
                            v-for="item in channel"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                          />
                        </el-select>
                      </el-col>
                    </el-form-item>
                  </el-row>
                </el-col>
                <el-col :span="24">
                  <el-row>
                    <el-col :span="4">
                      <span>分组</span>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item prop="group">
                        <el-input v-model="form.group" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="2">
                      <el-form-item prop="groupIndex">
                        <el-input-number v-model="form.groupIndex" :min="1" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="24">
                  <el-row>
                    <el-col :span="4">
                      <span>显示方向</span>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="direction">
                        <el-select v-model="form.direction">
                          <el-option
                            v-for="item in direction"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
              </el-col>
              <el-col :span="8">
                <el-image style="height:300px;float:right;" :src="getImageSrc(form.thumbnail)" alt="点击更换图片" fit="fill" @click="changeThumbnail">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" @click="changeThumbnail" />
                  </div>
                </el-image>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="22">
          <el-card shadow="always">
            <el-form-item>
              <span>编辑器</span>
              <el-radio v-model="form.editor" label="tinymce">Tinymce</el-radio>
              <el-radio v-model="form.editor" label="markdown">Markdown</el-radio>
            </el-form-item>
            <el-form-item>
              <tinymce-editor v-if="form.editor === 'tinymce'" ref="tinymce" v-model="form.content" :content="form.content" />
              <markdown-editor v-if="form.editor === 'markdown'" ref="markdown" v-model="form.content" :content="form.content" />
            </el-form-item>
          </el-card>
        </el-col>
        <el-col :span="22">
          <el-card shadow="always">
            <el-form-item>
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-form-item>
                    <span>标签</span>
                    <el-tag
                      v-for="tag in tags"
                      :key="tag"
                      closable
                      :disable-transitions="false"
                      @close="handleTagDelete(tag)"
                    >
                      {{ tag }}
                    </el-tag>
                    <el-input
                      v-if="inputTagVisible"
                      ref="saveTagInput"
                      v-model="inputTagValue"
                      class="input-new-tag"
                      size="small"
                      @keyup.enter.native="handleTagConfirm"
                      @blur="handleTagConfirm"
                    />
                    <el-button v-if="!inputTagVisible" class="button-new-tag" icon="el-icon-plus" @click="handleAddTag" />
                  </el-form-item>
                </el-col>
                <el-col :xs="{span: 6}" :sm="{span: 6}" :md="{span: 4}" :lg="{span: 4}" :xl="{span: 4}">
                  <span>权限&nbsp;&nbsp;&nbsp;&nbsp;</span>
                  <el-radio v-for="item in open" :key="item.dictCode" v-model="form.open" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-col>
                <el-col :xs="{span: 6}" :sm="{span: 6}" :md="{span: 4}" :lg="{span: 4}" :xl="{span: 4}">
                  <span>会员级别</span>
                  <el-select v-model="form.memberLevel">
                    <el-option
                      v-for="item in memberLevel"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </el-col>
                <el-col :xs="{span: 6}" :sm="{span: 6}" :md="{span: 4}" :lg="{span: 4}" :xl="{span: 4}">
                  <span>是否加密</span>
                  <el-radio v-for="item in crypto" :key="item.dictCode" v-model="form.crypto" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-col>
                <el-col v-if="form.crypto === '0'" :xs="{span: 2}" :sm="{span: 2}" :md="{span: 1}" :lg="{span: 1}" :xl="{span: 1}">
                  <span>分享码</span>
                </el-col>
                <el-col v-if="form.crypto === '0'" :xs="{span: 4}" :sm="{span: 4}" :md="{span: 3}" :lg="{span: 3}" :xl="{span: 3}">
                  <el-input v-model="form.salt" placeholder="请输入分享码" />
                </el-col>
                <!-- <el-col :xs="{span: 6}" :sm="{span: 6}" :md="{span: 4}" :lg="{span: 4}" :xl="{span: 4}">
                  <span>排序</span>
                  <el-input-number v-model="form.weight" :min="1" />
                </el-col> -->
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-tag type="success">⋅ 阅读 {{ form.views }} ⋅</el-tag>
              <el-tag type="success">⋅ 收藏 {{ form.favors }} ⋅</el-tag>
              <el-tag type="success">⋅ 评论 {{ form.views }} ⋅</el-tag>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit('0')">发 布</el-button>
            </el-form-item>
            <el-form-item>
              <el-col :span="10">
                <el-input v-model="video_url" placeholder="URL地址转码" />
              </el-col>
              <el-col :span="2" style="text-align: center;">
                <el-button type="primary" icon="el-icon-refresh" circle @click="translateURL" />
              </el-col>
              <el-col :span="10">
                <el-input v-model="video_url_encode" placeholder="转码后URL地址" />
              </el-col>
            </el-form-item>
          </el-card>
        </el-col>
      </el-form>
    </el-row>

    <el-dialog title="文章缩略图" :modal="false" :visible.sync="openThumbnail">
      <avatar-crop ref="thumbnailCrop" :upload-url="'/admin/article/uploadThumbnailFinal'" @setAvatar="setThumbnail" />
    </el-dialog>
  </div>
</template>

<script>
import TinymceEditor from '@/components/Tinymce'
import MarkdownEditor from '@/components/Markdown'
import AvatarCrop from '@/components/AvatarCrop'
import Login from '@/utils/login'

export default {
  name: 'ArticleForm',
  components: {
    TinymceEditor,
    MarkdownEditor,
    AvatarCrop
  },
  data() {
    return {
      redirect: undefined,
      form: {
        articleId: undefined,
        status: undefined,
        thumbnail: '',
        source: 'manual',
        title: undefined,
        summary: undefined,
        editor: 'markdown',
        content: undefined,
        open: '0',
        crypto: '1',
        memberLevel: '1',
        salt: undefined,
        // weight: 0,
        channel: undefined,
        direction: undefined,
        tags: '',
        views: 0,
        favors: 0,
        comments: 0,
        group: undefined,
        groupIndex: undefined
      },
      video_url: '',
      video_url_encode: '',
      rules: {
        title: [{ required: true, message: '请填写标题' }],
        channel: [{ required: true, message: '请选择栏目' }]
      },
      open: [],
      memberLevel: [],
      crypto: [],
      channel: [],
      direction: [],
      tags: [],
      inputTagValue: undefined,
      inputTagVisible: false,
      openThumbnail: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
        this.form.articleId = route.query && route.query.articleId
      },
      immediate: true
    },
    tags(value) {
      this.form.tags = this.tags.join(',')
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init(articleId) {
      // 加载下拉菜单
      this.getDictData()
      if (articleId) {
        this.form.articleId = articleId
      }
      this.$nextTick(() => {
        // 加载表单数据
        this.loadForm()
      })
    },
    getDictData() {
      this.$http.get('/admin/system/dict/dictGroup?group=blog_article_open').then(response => {
        this.open = response
      }).catch(e => {})
      this.$http.get('/admin/system/dict/dictGroup?group=member_level').then(response => {
        this.memberLevel = response
      }).catch(e => {})
      this.$http.get('/admin/system/dict/dictGroup?group=sys_yes_no').then(response => {
        this.crypto = response
      }).catch(e => {})
      this.$http.get('/admin/system/dict/dictGroup?group=blog_article_channel').then(response => {
        this.channel = response
      }).catch(e => {})
      this.$http.get('/admin/system/dict/dictGroup?group=blog_article_direction').then(response => {
        this.direction = response
      }).catch(e => {})
    },
    getImageSrc(value) {
      return this.$api.getImageSrc(value)
    },
    loadForm() {
      // 加载tinymce插件
      if (this.form.editor === 'tinymce') {
        this.$refs.tinymce.update('')
      }
      if (this.form.articleId) {
        this.$http.get('/admin/article/loadForm', {
          params: {
            'id': this.form.articleId
          }
        }).then(response => {
          this.form = this.$api.objectUpdate(this.form, response.param)
          this.form.memberLevel = response.param.memberLevel + ''
          if (this.form.tags) {
            this.tags = this.form.tags.split(',')
          }
          this.$refs.tinymce.update(this.form.content)
        }).catch(() => {})
      }
    },
    changeEditor(value) {
      if (this.form.editor === 'tinymce') {
        this.$refs.tinymce.update('')
        this.$refs.tinymce.update(this.form.content)
      }
    },
    changeThumbnail() {
      this.openThumbnail = true
      this.$nextTick(() => {
        let avatarUrl
        if (this.form.thumbnail) {
          avatarUrl = '/admin/common/preview/' + this.form.thumbnail
        } else {
          avatarUrl = ''
        }
        this.$refs.thumbnailCrop.init(avatarUrl)
      })
    },
    setThumbnail(avatarId) {
      this.form.thumbnail = avatarId
      this.openThumbnail = false
    },
    translateURL() {
      if (this.video_url) {
        this.video_url_encode = encodeURI(this.video_url)
      }
    },
    handleAddTag() {
      this.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleTagConfirm() {
      const inputValue = this.inputTagValue
      if (inputValue) {
        this.tags.push(inputValue)
      }
      this.inputTagVisible = false
      this.inputTagValue = ''
    },
    handleTagDelete(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1)
    },
    onSubmit(type) {
      // eslint-disable-next-line no-unused-vars
      let close = false
      if (type === '0' || type === '1') {
        close = true
      }

      if (!this.form.content) {
        this.$message({
          type: 'warining',
          message: '请输入文章内容'
        })
        return false
      }

      this.form.status = type
      // 判断是否加密
      if (this.form.crypto === '0') {
        if (!this.form.salt) {
          this.$message({
            type: 'warining',
            message: '请输入分享码'
          })
          return false
        }
        this.form.content = Login.Encrypt(this.form.content)
        if (this.form.summary) {
          this.form.summary = Login.Encrypt(this.form.summary)
        }
      }

      this.$refs.articleFormRef.validate(valid => {
        if (valid) {
          this.$http.post('/admin/article/saveForm', this.form).then(response => {
            this.$message({
              type: 'success',
              message: response.msg
            })
            if (close) {
              this.onClose()
              this.$router.push({ path: this.redirect || '/' })
            }
          }).catch(() => {})
        } else {
          return false
        }
      })
    },
    onClose() {
      if (this.form.editor === 'tinymce') {
        this.$refs.tinymce.update('')
      }
      this.form = {
        articleId: undefined,
        status: undefined,
        thumbnail: '',
        source: 'manual',
        title: undefined,
        summary: undefined,
        editor: 'tinymce',
        content: undefined,
        open: '0',
        crypto: '1',
        memberLevel: '1',
        salt: undefined,
        // weight: 0,
        channel: undefined,
        direction: undefined,
        tags: '',
        views: 0,
        favors: 0,
        comments: 0,
        group: undefined,
        groupIndex: undefined
      }

      this.video_url = ''
      this.video_url_encode = ''
      this.tags = []
      this.inputTagValue = undefined
      this.inputTagVisible = false
      this.openThumbnail = false
    }
  }
}
</script>
